package controllers;

import helpers.CrawlerHelper;
import helpers.FileHelper;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import systems.RecentlyArticle;

import entities.Page;

public class HomeServlet extends HttpServlet {
	public void doGet(HttpServletRequest request, HttpServletResponse response)
		throws IOException, ServletException {
		
		String uri = request.getRequestURI();
		
		String url = "http://www.nlm.nih.gov";
		
		String pageJsp = "/pages/home.jsp";
		
		if (uri.equalsIgnoreCase("/")) {
			url += "/medlineplus/healthtopics_a.html";
		} else {
			url += uri;
		}
		
		/*Page page = new Page();
		
		page = FileHelper.getPageByFileName(url);*/
		
		Page page = null;
		
		if (page == null) {
			if (url.contains("healthtopics_")) {
				page = CrawlerHelper.getContentTopic(url);
			} else {
				pageJsp = "/pages/info.jsp";
				page = CrawlerHelper.getContent(url);
			}
			
			if (!page.getContent().isEmpty()) {
				//FileHelper.saveCurrentPage(page);
			}
		} else {
			if (!url.contains("healthtopics_")) {
				pageJsp = "/pages/info.jsp";
			}
		}
		
		if (page != null && !page.getTitle().isEmpty()) {
			RecentlyArticle.insert(page.getTitle(), uri);
		}
		
		request.setAttribute("page", page);
		try {
			request.getRequestDispatcher(pageJsp).forward(request, response);
		} catch (ServletException e) {
			//e.printStackTrace();
		}
	}
}
